<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户收藏的泰山号动态格式化
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000016_t_sns_dynamic_ts_favorite_format extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_favorite}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)
        ->where(['model' => 'ts_dynamic']);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        $ids = [];
        foreach ($rows as $row) {
            $nowid = (new Query())->from('{{%sns_dynamic}}')
            ->select('id')
            ->where(['topic_id' => $row['model_id']])
            ->scalar();
            if (!$nowid) {
                $ids[] = $row['id'];
            } else {
                $migration->db->createCommand()->update($migration->tableName, [
                    'model' => 'sns_dynamic',
                    'model_id' => $nowid,
                ], ['id' => $row['id']])->execute();
            }
        }
        if (!empty($ids)) {
            $connect->delete($migration->tableName, ['id' => $ids])->execute();
        }
    }

}
